<?php
namespace app\shop\controller;
use app\ApiRest;
use app\BaseController;
use app\helppay\model\Helppay;
use app\member\model\Config;
use app\member\model\Goods;
use app\member\model\Integral;
use app\member\model\Member;
use app\member\model\StoredOrder;
use app\publics\model\TmplConfig;
use app\shop\model\BargainRecord;
use app\shop\model\Printer;
use longbingcore\wxcore\WxTmpl;
use think\App;
use think\facade\Db;
use app\shop\model\IndexShopOrder as OrderModel;
use app\shop\model\IndexUserInfo;
use app\shop\model\IndexUser;
use app\shop\model\IndexGoods;
use app\shop\model\IndexShopSpePrice;
use app\shop\model\IndexAddress;
use app\shop\model\IndexShopOrderGoods;
use app\shop\model\IndexCouponRecord;
use app\shop\model\IndexShopCollageList;
use app\shop\model\IndexUserCollage;
use app\shop\model\IndexSellingProfit;
use app\shop\model\IndexSellingWater;
use app\shop\model\IndexCardCount;
use work;


class IndexPayResunt extends BaseController
{

    public $model;
    public $user_info_model;
    public $goods_model;
    public $spe_price_model;
    public $address_model;
    public $order_goods_model;
    public $coupon_record_model;
    public $collage_list_model;
    public $user_collage_model;
    public $user_model;
    public $profit_model;
    public $water_model;
    public $count_model;
    protected $_config = [];


    public function __construct(App $app) {
        parent::__construct($app);
        $this->model              = new OrderModel();
        $this->user_info_model    = new IndexUserInfo();
        $this->goods_model        = new IndexGoods();
        $this->spe_price_model    = new IndexShopSpePrice();
        $this->address_model      = new IndexAddress();
        $this->order_goods_model  = new IndexShopOrderGoods();
        $this->coupon_record_model= new IndexCouponRecord();
        $this->collage_list_model = new IndexShopCollageList();
        $this->user_collage_model = new IndexUserCollage();
        $this->user_model         = new IndexUser();
        $this->profit_model       = new IndexSellingProfit();
        $this->water_model        = new IndexSellingWater();
        $this->count_model        = new IndexCardCount();

        if ( defined( 'IS_WEIQIN' ) ) {
            global $_GPC, $_W;
            $this->_uniacid = $_W[ 'uniacid' ];
        } else {
            $this->_uniacid = 7777;

        }
       // $this->_config = longbingGetAppConfig($this->_uniacid);
    }



    public function payResult(){



        dump(1);exit;
        $datas = $_POST;

        if(!empty($datas)){

            $datas = serialize($datas);

            $this->model->orderUpdate(['id'=>22],['remarks'=>$datas]);

        }

        $b = json_decode( $this->request->getInput(), true );

        if(!empty($b)){

            $b = serialize($b);

            $this->model->orderUpdate(['id'=>22],['remarks'=>$b]);

        }

        dump($datas,$b);exit;


    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-21 14:21
     * @功能说明:代付支付回调
     */
    public function helpPayResunt($arr='',$transaction_id=''){

        $help_model = new Helppay();

        $info = $help_model->dataInfo(['order_code'=>$arr['out_trade_no']]);

        if(empty($info)||$info['status']==1||!empty($info['cancel_transaction_id'])){

            return false;

        }

        $order = $this->model->orderInfo(['id'=>$info['order_id']]);

        $update = [

            'pay_time' => time(),

            'transaction_id' => $transaction_id,

            'status' => 1
        ];
        //修改代付调状态
        $help_model->dataUpdate(['id'=>$info['id']],$update);
        //原本订单调回调
        $this->payResunt(['out_trade_no'=>$order['out_trade_no']],$transaction_id,$info['id']);

        return true;

    }

    /**
     * User: chenniang
     * Date: 2019-09-10 10:09
     * @param string $arr
     * @param string $transaction_id
     * @return bool
     * descption:支付回调
     */
    public function payResunt($arr='',$transaction_id='',$help_id=-1){

            $order  = $this->model->orderInfo(['out_trade_no' => $arr['out_trade_no']]);
            //查看有没有代付的 有的话就把代付的退了
            $this->checkHelpPay($order,$help_id,$transaction_id);

            $this->_uniacid = $order['uniacid'];

            if ( !$order || $order[ 'pay_status' ] != 0 ) {

                return false;
            }

            $update = [

                'pay_status'     => 1,

                'transaction_id' => $transaction_id,
                //代付id
                'help_pay_id'    => $help_id,
                //是否是代付订单
                'help_pay'       => $help_id>0?1:0

            ];

            $this->model->orderUpdate(['id'=>$order['id']],$update);

            if ($order[ 'type' ] == 1) {

                $collage_info   = $this->collage_list_model->collageInfo([ 'id' => $order[ 'collage_id' ]]);

                $collage_status = $collage_info[ 'left_number' ] <= 0?2:1;

                $this->collage_list_model->collageUpdate([ 'id' => $order['collage_id']],['collage_status' => $collage_status]);

                $this->user_collage_model->collageUpdate([ 'collage_id' => $order['collage_id']],['collage_status' => $collage_status]);
            }

            $items = $this->order_goods_model->orderGoodsInfo(['order_id' => $order[ 'id' ]]);

            foreach ($items as $k => $v) {

                $num = $v['number'];

                if ($order[ 'type' ] == 1) {

                    $this->goods_model->goodsUpdate(['id'=>$v[ 'goods_id' ]],['collage_count'=>Db::raw("collage_count+$num")]);
                }

            }

            $mark = Db::name('longbing_card_user_mark')->where(['user_id'=> $order[ 'user_id' ], 'staff_id' => $order[ 'to_uid' ]])->find();

            if (empty($mark)) {
                $mark_data = [
                        'user_id'     => $order[ 'user_id' ],
                        'staff_id'    => $order[ 'to_uid' ],
                        'mark'        => 2,
                        'status'      => 1,
                        'uniacid'     => $order['uniacid'],
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                Db::name('longbing_card_user_mark')->insert($mark_data);

            } else {

                Db::name('longbing_card_user_mark')->where(['id'=>$mark['id']])->update(['mark'=> 2,'update_time'=>time()]);
            }

            $member_config_model = new Config();
            //会员配置
            $member_config = $member_config_model->configInfo(['uniacid'=>$order['uniacid']]);
            //砍价活动不参与分销
            if(($order['type']!=1&&($order['stored']==0))||($order['type']!=1&&$order['stored']>0&&in_array($member_config['commission_type'],['2','3']))){

                if($order['is_bargain']==0&&$order['total_price']>0){

                    $res = $this->updateWater($order);

                }
            }

            $res = $this->payNoticeClient($order);

            $res = $this->payNoticeStaff($order);

            $res = $this->sendService($order);

            $member_model = new Member();
            //会员购买商品
            $member_model->memberPayResult($order);
            //如果是砍价订单 需要改变砍价记录的状态
            if($order['is_bargain']==1){

                $bargain_model = new BargainRecord();

                $bargain_model->dataUpdate(['order_id'=>$order['id']],['status'=>3]);

            }
            //积分抵扣
            if($order['integral']>0){

                $i_model = new Integral();

                $i_model->incUserIntegral($order['id'],$order['user_id'],$order['uniacid'],3);
            }

            $printer_model = new Printer();

            $printer_model->printer($order['id']);

            return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-26 17:19
     * @功能说明:检查代付情况
     *
     */
    public function checkHelpPay($order,$help_id,$transaction_id){
        //说明已经有人付款过 并且付款人不是我 需要退款
        if ($order[ 'pay_status' ] != 0&&$order['help_pay_id']!=$help_id) {

            $help_model = new Helppay();

            if($help_id>0){
                //说明是代付
                $help_model->refund($help_id);

            }else{
                $order['transaction_id'] = $transaction_id;
                //自己付
                $help_model->refundOrder($order);

            }

        }

        return true;

    }




    /**
     * @author chenniang
     * @DataTime: 2020-09-17 10:19
     * @功能说明:储值支付回调
     */
    public function orderStoredResult($order,$type,$stored=0){
        //增加储值支付记录
        if($order['stored']>0){

            $member_model      = new Member();
            //会员信息
            $member = $member_model->memberUpdateInfo(['user_id' => $order['user_id'],'uniacid'=>$order['uniacid']]);
            //商品子订单
            $order_goods = $this->order_goods_model->orderGoodsInfo(['order_id' => $order[ 'id' ]]);
            //商品名字
            $title = array_column($order_goods,'name');

            $title = substr(implode('-',$title),0,200);

            $store_order_model = new StoredOrder();

            $stored = !empty($stored)?$stored:$order['stored'];
            //增加记录
            $store_order_model->desStore($stored,'',$member,$type,$order['to_uid'],$order['out_trade_no'],$title);
        }
        return true;
    }


    /**
     * @param $order
     * @return bool
     * 编辑流水
     */
    protected function updateWater ( $order ){

        $order_item = $this->order_goods_model->orderGoodsInfo([ 'order_id' => $order[ 'id' ] ]);

        foreach ( $order_item as $index => $item ) {

            $pay_price = !empty($item['version'])?$item[ 'pay_price' ]:$item[ 'price' ];

            $this->insertWater( $order, $pay_price, $item, $item[ 'name' ], $item['cover'][0] );

        }

        return true;
    }
    /**
     * @param $order
     * @param $price
     * @param $item
     * @param string $title
     * @param string $img
     * @return bool
     * 编辑流水
     */
    protected function insertWater ( $order, $price, $item, $title = '', $img = '' ){
        //uniacid
        $this->_uniacid = $item['uniacid'];
        //用户id
        $user_id  = $order[ 'user_id' ];
        //员工id
        $staff_id = $order[ 'to_uid' ];
        //商品信息
        $goods    = $this->goods_model->goodsInfo([ 'id' => $item[ 'goods_id' ] ] );
        //配置信息
        $this->_config = longbingGetAppConfig($this->_uniacid);
        //判断配置信息
        if ( !$this->_config || !$goods ) {
            return false;
        }
        //  员工提成
        if ( $staff_id && $goods[ 'staff_switch' ]!=0) {
            //员工信息
            $staff       = $this->user_model->userInfos(['id' => $staff_id ]);
            //检查有无分销记录
            $check_staff = $this->profit_model->profitInfo([ 'user_id' => $staff_id ] );
            //没有则添加
            if (!$check_staff) {
                $this->profit_model->profitAdd(['user_id' => $staff_id, 'uniacid'=> $this->_uniacid]);
            }

            if ($staff) {
                //如果使用的是自定义金额
                if($goods[ 'staff_switch' ]==2){
                    //比列
                    $staff_extract = 0;
                    //金额
                    $extract_money = round($goods['staff_extract_cash']*$item[ 'number' ],2);
                    //分销方式
                    $selling_type  = 1;
                //如果使用的是比列
                }elseif($goods[ 'staff_switch' ]==1){
                    //比列
                    $staff_extract = $goods[ 'staff_extract' ];
                    //金额
                    $extract_money = round($price * $staff_extract / 100,2);
                    //分销方式
                    $selling_type  = 0;
                }else{
                    //如果使用的是全局
                    if($this->_config['selling_style']==1){
                        //比列
                        $staff_extract = $this->_config[ 'staff_extract' ];
                        //金额
                        $extract_money = round($price * $staff_extract / 100,2);
                        //分销方式
                        $selling_type  = 0;
                    //如果使用的是金额
                    }elseif ($this->_config['selling_style']==2){
                        //比列
                        $staff_extract = 0;
                        //金额
                        $extract_money = round($this->_config['staff_extract_cash']*$item[ 'number' ],2);
                        //分销方式
                        $selling_type  = 1;
                    }else{
                        //比列
                        $staff_extract = 0;
                        //金额
                        $extract_money = 0;
                        //分销方式
                        $selling_type  = 0;
                    }
                }
                if($staff_extract!=0||$extract_money!=0) {

                    $this->profit_model->profitUpdate(['user_id' => $staff_id ],[ 'waiting' => Db::raw("waiting+$extract_money")]);

                    $insert_data = [
                        'user_id'     => $staff_id,
                        'source_id'   => $user_id,
                        'order_id'    => $order[ 'id' ],
                        'goods_id'    => $item[ 'goods_id' ],
                        'buy_number'  => $item[ 'number' ],
                        'type'        => 1,
                        'title'       => $title,
                        'img'         => $img,
                        'price'       => $price,
                        'extract'     => $staff_extract,
                        'waiting'     => 1,
                        'uniacid'     => $this->_uniacid,
                        'selling_type'=> $selling_type,
                        'extract_cash'=> $extract_money
                    ];
                    $this->water_model->waterAdd($insert_data);
                }
            }
        }
        //判断是否关闭
        if ( $goods[ 'switch' ] == 0 ) {
            return false;
        }

        $user = $this->user_model->userInfos([ 'id' => $user_id ]);
        //  一级上线提成
        if (!empty($user[ 'pid' ])&& $user['pid'] != $staff_id ) {

            $p_user = $this->user_model->userInfos([ 'id' => $user['pid'] ]);

            if (empty($p_user)||$p_user['is_staff']==1) {

                return false;
            }
            $config_model = new \app\shop\model\AdminShopSetting();
            //查看配置
            $config = $config_model->configInfo(['uniacid'=>$this->_uniacid]);

            if(!empty($config)&&$config['distribution_user_examine']==1){

                $user_a = Db::name('longbing_card_distributor_application')->where(['user_id'=>$user[ 'pid' ],'status'=>1])->find();

                if(empty($user_a)){

                    return false;
                }
            }

            $check_first = $this->profit_model->profitInfo([ 'user_id' => $user[ 'pid' ] ]);

            if ( !$check_first ) {

                $this->profit_model->profitAdd(['user_id'=>$user[ 'pid' ],'uniacid'=>$this->_uniacid]);
            }
            //如果使用的是自定义金额
            if($goods[ 'switch' ]==2){
                //比列
                $extract = 0;
                //金额
                $extract_money = round($goods['extract_cash']*$item[ 'number' ],2);
                //分销方式
                $selling_type  = 1;
                //如果使用的是比列
            }elseif($goods[ 'switch' ]==1){
                //比列
                $extract = $goods[ 'extract' ];
                //金额
                $extract_money = sprintf( "%.2f", $price * $extract / 100 );
                //分销方式
                $selling_type  = 0;
            }else{
                //如果使用的是全局
                if($this->_config['selling_style']==1){
                    //比列
                    $extract = $this->_config[ 'first_extract' ];
                    //金额
                    $extract_money = sprintf( "%.2f", $price * $extract / 100 );
                    //分销方式
                    $selling_type  = 0;
                    //如果使用的是金额
                }elseif ($this->_config['selling_style']==2){
                    //比列
                    $extract = 0;
                    //金额
                    $extract_money = round($this->_config['first_extract_cash']*$item[ 'number' ],2);
                    //分销方式
                    $selling_type  = 1;
                }else{
                    //比列
                    $extract = 0;
                    //金额
                    $extract_money = 0;
                    //分销方式
                    $selling_type  = 0;
                }
            }

            if($extract!=0||$extract_money!=0){
                $this->profit_model->profitUpdate(['user_id' => $user[ 'pid' ]],['waiting'=>Db::raw("waiting+$extract_money")]);

                $insert_data = [
                    'user_id'     => $user[ 'pid' ],
                    'source_id'   => $user_id,
                    'order_id'    => $order[ 'id' ],
                    'goods_id'    => $item[ 'goods_id' ],
                    'buy_number'  => $item[ 'number' ],
                    'type'        => 2,
                    'title'       => $title,
                    'img'         => $img,
                    'price'       => $price,
                    'extract'     => $extract,
                    'waiting'     => 1,
                    'uniacid'     => $this->_uniacid,
                    'selling_type'=> $selling_type,
                    'extract_cash'=> $extract_money
                ];

                $this->water_model->waterAdd($insert_data);
                $user = $this->user_model->userInfos(['id'=>$user['pid']]);//给上级发送模版消息
                $send_data['open_id']   = $user['openid'];
                $send_data['uniacid']   = $this->_uniacid;
                $send_data['form_id']   = $this->getFormId($user['id']);

                $send_data['nickName']  = $user['nickName'];
                $send_data['send_body'] = '您的下线在商品消费啦';
                $send_data['page_data'] = 'longbing_card/voucher/pages/user/myearning/myearning';

                longbingSendWxServiceNoticeBase($send_data);
            }

        }
        return true;
    }

    /**
     * User: chenniang
     * Date: 2019-09-10 15:13
     * @param $order
     * @param string $sign
     * @return bool
     * descption: 发送客户端消息
     */
    public function payNoticeClient($order, $sign = 'normal'){
        $user = $this->user_model->userInfos(['id'=>$order['user_id']]);//给上级发送模版消息
        $this->_uniacid = !empty($user['uniacid'])?$user['uniacid']:$this->_uniacid;
        $send_data['open_id']   = $user['openid'];
        $send_data['uniacid']   = $this->_uniacid;
        $send_data['form_id']   = $this->getFormId($user['id']);
        $send_data['nickName']  = $user['nickName'];
        $send_data['send_body'] = '支付成功';
        $send_data['page_data'] = 'longbing_card/voucher/pages/user/myearning/myearning';
        if ( $order[ 'type' ] === 1 ) {
            $items = $this->order_goods_model->orderGoodsInfo(['order_id' => $order[ 'id' ]]);
            $send_data['page_data'] = 'longbing_card/pages/shop/releaseCollage/releaseCollage?id=' . $items[0][ 'goods_id' ] . '&status=toShare&to_uid=' . $order[ 'to_uid' ] . '&collage_id=' . $order[ 'collage_id' ];
        }
        //  扫码支付
        if ($sign == 'qr') {
            $send_data['page_data'] = 'longbing_card/pages/index/index?to_uid=' . $order[ 'staff_id' ] . '&currentTabBar=toCard';
        }
        $res = longbingSendWxServiceNoticeBase($send_data);
        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-01-03 11:59
     * @功能说明:测试专用
     */
    public function test(){


       $a =  $this->getSassNum('activity',4);
        dump($a);exit;

        $order = $this->model->orderInfo(['id'=>1301]);
//        $a = $this->payResunt(['out_trade_no'=>'2020010215493304000000001301'],'111');
        $order = $this->sendService($order,'activity');

        dump($order);exit;

    }


    /**
     * @author chenniang
     * @DataTime: 2019-12-27 19:19
     * @功能说明:发送订阅消息
     */
    public function sendService($order){
        //获取用户的open_id
        $openid = $this->user_model->where(['id'=>$order['user_id']])->value('openid');

        $is_staff = $this->user_model->where(['id'=>$order['user_id']])->value('is_staff');
        //访问页面
//        $page = $is_staff==1?'/shop/pages/order/list?target=staff':'/shop/pages/order/list';
        $page = '/shop/pages/order/list';
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->where(['uniacid'=>$order['uniacid'],'tmpl_name'=>'pay_order'])->find();
        //如果未添加模版消息 则不发送
        if(empty($tmpl)){
            return true;
        }else{
            $tmpl = $tmpl->toArray();
        }
        //模版id
        $tmpl_id = $tmpl['tmpl_id'];
//        //模版类容
//        $key_worlds = $tmpl['kidList'];
        $service_model = new WxTmpl($order['uniacid']);
        //模版的key
        $key_worlds    = $service_model::getTmplKey($tmpl_id);

        if(!empty($openid)&&!empty($tmpl_id)&&!empty($key_worlds)){

            //验证模版内容
            if(!is_array($key_worlds)||count($key_worlds)<4){
                return true;
            }
            //发送内容
            $send_data = array(
                $key_worlds[1]=>array(
                    //商品名称
                    'value'=>implode(',',array_column($order['goods_text']['goods'],'name')),
                ),
                $key_worlds[2]=>array(
                    //商品价格
                    'value'=>$order['total_price'],
                ),
                $key_worlds[3]=>array(
                    //支付金额
                    'value'=>$order['out_trade_no'],
                ),
                $key_worlds[4]=>array(
                    //支付时间
                    'value'=>date('Y-m-d H:i:s',$order['create_time']),
                ),
            );
            //模版消息库类
            $tmpl_sever = new WxTmpl($order['uniacid']);
            //发送模版消息
           $res = $tmpl_sever::sendTmpl($openid,$tmpl_id,$send_data,$page);
          // dump($res);exit;

        }
        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-10 15:14
     * @param $order
     * @param string $sign
     * @return bool
     * descption: 发送员工端消息
     */
    public function payNoticeStaff( $order, $sign = 'normal' ){
        if($sign == 'qr'){
            $type = 1;
            $sign = 'qr';
        }else{
            $sign = 'order';
            $type = $order[ 'type' ] ==1?2:1;
        }
        $inset_data = [
            'user_id' => $order[ 'user_id' ],
            'to_uid'  => $order[ 'to_uid' ],
            'type'    => $type,
            'sign'    => $sign,
            'target'  => $order[ 'id' ],
            'uniacid' => $order[ 'uniacid' ]
        ];
        $insert_id = $this->count_model->countAdd($inset_data);
        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',
            'event'   => 'longbingSendWxServiceNotice',
            'count_id'=> $insert_id
        );
        publisher(json_encode($push_data ,true));
        return true;
    }

    /**
     * @Purpose: 获取formId
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */

    public function getFormId ( $to_uid )
    {
        return [];
        // 七天前开始的的时间戳
        // $beginTime = mktime( 0, 0, 0, date( 'm' ), date( 'd' ) - 6, date( 'Y' ) );
        $beginTime = strtotime(date('Y-m-d',time()))-86400*6;
        $formId    = Db::name( 'longbing_card_formId' )
            ->where( [ 'user_id' => $to_uid ] )
            ->order( 'id desc' )
            ->select();
        if ( empty( $formId ) )
        {
            return false;
        }
        if ( $formId[ 0 ][ 'create_time' ] < $beginTime )
        {
            Db::name( 'longbing_card_formId' )
                ->where( [ 'id' => $formId[ 0 ][ 'id' ] ] )
                ->delete();
            $this->getFormId( $to_uid );
        }
        else
        {
            Db::name( 'longbing_card_formId' )
                ->where( [ 'id' => $formId[ 0 ][ 'id' ] ] )
                ->delete();
            return $formId[ 0 ][ 'formId' ];
        }
    }


}
